package net.cl.support.codec;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import net.cl.utils.ByteUtil;
import net.cl.utils.StringUtil;

/**
 * Data Encryption Standard 数据加密标准
 * 
 * @author caol64@gmail.com
 */
public class DES {
	/**
	 * 解密
	 */
	public static String decrypt(String data, String key) {
		key = StringUtil.addLeft(key, '0', 8);
		byte[] result = DESMain(ByteUtil.hexString2Bytes(data), key.getBytes(), Cipher.DECRYPT_MODE);
		return new String(result);
	}

	/**
	 * 加密
	 */
	public static String encrypt(String data, String key) {
		key = StringUtil.addLeft(key, '0', 8);
		byte[] result = DESMain(data.getBytes(), key.getBytes(), Cipher.ENCRYPT_MODE);
		return ByteUtil.bytes2HexString(result);
	}

	private static byte[] DESMain(byte[] data, byte[] key, int mode) {
		try {
			SecureRandom sr = new SecureRandom();
			DESKeySpec dks = new DESKeySpec(key);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(dks);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(mode, securekey, sr);
			return cipher.doFinal(data);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static void main(String[] args) {
		System.out.println(encrypt("123","123"));
	}

}
